<?php

namespace app\share\model;

use think\Db;
use think\Model;

class UploadImg extends Model
{
    //excel导入
    public function uploadPicture($url,$userId)
    {
        try{
            //拿到excel绝对路径
            $php_excel =  $url;
            $php_obj = new PhpExecl();
            //拿到excel的数据
            $excelData = $php_obj->readData($php_excel);
            //判断后循环插入数据库
            $sum_num = count($excelData);
            //判断数据超过2000提示不合法
            if($sum_num > 5000)
            {
                returnJson(-2002,  "excel数据不能超过5000条,请调整后重新上传")->send();die;
            }
            if($sum_num == 0)
            {
                returnJson(-2003,  "excel数据为空,请编辑后上传")->send();die;
            }

            //插入进度条总数量
            $where_exist['user_id'] = $userId;
            $user_exist = Db::name("set_pro")->where($where_exist)->find();
            if($user_exist)
            {
                Db::name("set_pro")->where($where_exist)->update(['pro_sum'=>$sum_num]);
            }else
            {
                Db::name("set_pro")->insert(['pro_sum'=>$sum_num, 'user_id'=>$userId]);
            }
            $success_num = 0;
            $repeat_num  = 0;
            $error_num   = 0;

            //当前进度数目
            $pro_num     = 0;//当前进度条数
            foreach ($excelData as $data)
            {
                $ping['net_name']   = trim($data['1']);
                $ping['ip_server']  = trim($data['2']);
                $ping['company_id']  = trim($data['3']);
                $ping['depart_id']  = trim($data['4']);
                $ping['ip_address'] = trim($data['5']);
                $ping['ip_remark']  = trim($data['6']);
                $ping['ip_user']    = $userId;
                $ping['ip_update']  = time();
                //去重判断
                if(isset($ping['ip_address']))
                {
                    $where['ip_address'] = $ping['ip_address'];
//                    $res1 = Db::name("batch_ip_log")->where($where)->order(['ip_id'=>'desc'])->find();
                    $res2 = Db::name("ip_store")->where($where)->order(['ip_id'=>'desc'])->find();
                    if($res2)
                    {
                        ++$repeat_num;
                        //当前进度数目
                        ++$pro_num;
                        Db::name("set_pro")->where($where_exist)->update(['pro_num'=>$pro_num]);

                        continue;
                    }
                    //ip地址格式判断
                    if( filter_var( $ping['ip_address'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ){        //IPv6
                    }elseif( filter_var( $ping['ip_address'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) ){    //IPv4
                    }else{
                        $ping['ip_note'] = "ip地址格式错误";
                        $ping['ip_status'] = 3;
                        //写入记录表
                        ++$error_num;
                        Db::name("batch_ip_log")->insert($ping);
                        //当前进度数目
                        ++$pro_num;
                        Db::name("set_pro")->where($where_exist)->update(['pro_num'=>$pro_num]);

                        continue;
                    }
                }
                //网络服务商id,必须存在
                if(isset($ping['ip_address']))
                {
                    $serverId['server_id'] = $ping['ip_server'];
                    $res3 = Db::name("server_name")->where($serverId)->find();
                    if(empty($res3))
                    {
                        ++$error_num;
                        $ping['ip_note'] = "网络服务商id不存在";
                        $ping['ip_status'] = 3;
                        //写入记录表
                        Db::name("batch_ip_log")->insert($ping);

                        //当前进度数目
                        ++$pro_num;
                        Db::name("set_pro")->where($where_exist)->update(['pro_num'=>$pro_num]);

                        continue;
                    }

                    //单位id必须存在
                    $company_id['company_id'] = $ping['company_id'];
                    $company_res = Db::name("company")->where($company_id)->count();
                    if(empty($company_res))
                    {
                        ++$error_num;
                        $ping['ip_note'] = "单位不存在";
                        $ping['ip_status'] = 3;
                        //写入记录表
                        Db::name("batch_ip_log")->insert($ping);

                        //当前进度数目
                        ++$pro_num;
                        Db::name("set_pro")->where($where_exist)->update(['pro_num'=>$pro_num]);

                        continue;
                    }

                    //部门id必须存在
                    $depart_id['company_id'] = $ping['depart_id'];
                    $depart_res = Db::name("company")->where($depart_id)->count();
                    if(empty($depart_res))
                    {
                        ++$error_num;
                        $ping['ip_note'] = "部门不存在";
                        $ping['ip_status'] = 3;
                        //写入记录表
                        Db::name("batch_ip_log")->insert($ping);

                        //当前进度数目
                        ++$pro_num;
                        Db::name("set_pro")->where($where_exist)->update(['pro_num'=>$pro_num]);

                        continue;
                    }


                }
                if(empty($ping['depart_id']) || empty($ping['net_name']) || empty($ping['ip_server']) || empty($ping['ip_address']) || empty($ping['company_id']))
                {

                    $ping['ip_note'] = "必填数据为空";
                    $ping['ip_status'] = 3;
                    //写入记录表
                    ++$error_num;
                    Db::name("batch_ip_log")->insert($ping);

                    //当前进度数目
                    ++$pro_num;
                    Db::name("set_pro")->where($where_exist)->update(['pro_num'=>$pro_num]);

                    continue;
                }else
                {
                    //验证都通过,写入2个数据库
                    ++$success_num;
                    $ping['ip_note'] = "";
                    $ping['ip_status'] = 1;
                    $ping['ip_remark'] = empty($ping['ip_remark']) ? "批量导入" : $ping['ip_remark'];

                    //当前进度数目
                    ++$pro_num;
                    Db::name("set_pro")->where($where_exist)->update(['pro_num'=>$pro_num]);

                    Db::name("ip_store")->insert($ping);

                    Db::name("batch_ip_log")->insert($ping);
                }
            }
            //文件导入成功后删除文件
            unlink($url);
            $result['sum_num']     = $sum_num;
            $result['success_num'] = $success_num;
            $result['repeat_num']  = $repeat_num;
            $result['error_num']   = $error_num;
            returnJson(200,  "导入完毕", $result)->send();die;
        }catch(\Exception $e)
        {
            returnJson(-3001,  "模板文件格式错误,请使用官方指定模板")->send();die;
        }

    }

    public function uploadExcel($file)
    {
        $arr_suffix = ['xls', 'xlsx'];
        $img_suffix = strtolower( pathinfo( $file['name'],PATHINFO_EXTENSION ) );
        if( !in_array( $img_suffix, $arr_suffix, true ) )
        {
            return ['code'=>-2001, 'msg'=>"文件不合法，仅支持xls,xlsx的文件"];
        }
        if ($file['error'] == 0)
        {
            $fileame = date("YmdHis").uniqid("qc").".".pathinfo($file['name'],PATHINFO_EXTENSION);
            $php_excel =  self::uploadLocal($file,$fileame);
            returnJson(200,  "success", ['url'=>$php_excel])->send();die;

        }

    }


    private function uploadLocal($file, $filename)
    {
        $path = ROOT_PATH."public".DS."uploads".DS.date('Ymd').DS; //
        if(!file_exists($path))
        {
            mkdir($path,0777,true);
        }
        $path = $path.$filename;
        $moveRs = move_uploaded_file($file['tmp_name'],$path);
        if($moveRs){
            $rs = str_replace("\\", '/', ROOT_PATH ."public".DS."uploads".DS.date('Ymd').DS.$filename);
            return $rs;
        }
    }




}